package com.mk.cloud.common.util;

import com.mk.cloud.common.enums.GlobalValues;

import java.security.MessageDigest;

/**
 * Created by cc on 2016/11/11 0011.
 */
@SuppressWarnings("unused")
public class EncyUtils {
    /**
     * MD5加密，自动追加key
     * 适用于大多数加密情况（如密码、密码提示等）
     *
     * @param s
     * @return
     */
    public static String MD5(String s) {
        return MD5(s, "fin123ancial4569-+=");
    }

    /**
     * MD5加密，手动指定加密key
     *
     * @param s
     * @param key
     * @return
     */
    public static String MD5(String s, String key) {
        s += key;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes(GlobalValues.CHARSET_UTF8.value());
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String MD5(String s, String... keys) {
        StringBuilder sBuilder = new StringBuilder(s);
        for(String key : keys){
            sBuilder.append(key);
        }
        s = sBuilder.toString();
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes(GlobalValues.CHARSET_UTF8.value());
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成六位数随机密码
     *
     * @return
     */
    public static String getInitPassWord() {
        int i = (int) ((Math.random() * 9 + 1) * 100000);
        return String.valueOf(i);
    }

}
